# $Id: $


package Zuz::Action::Login;

use base qw(Zuz::Action);
use strict;
use warnings;

use Zuz::Users;
use Zuz::Sessions;
use Dancer ':syntax';
use Digest::MD5 qw/md5_hex/;


sub is_auth_required {
	my $self = shift;

	return 0;
}


sub generate_content {
	my $self = shift;

	if (request->method() eq "GET") {
		# Go to start page if user is already logged in.
		if ( $self->is_user_logged_in ) {
			my $type = $self->get_user_type;
			redirect "/$type/start";
		}
		else {
			template 'login.tt';
		}
	}
	elsif (request->method() eq "POST") {

		my $login    = params->{login};
		my $password = params->{password};

		my $password_hex = md5_hex($login.$password.'dancer');
		my %data = (login => $login, password => $password_hex);
		my $user = Zuz::Users->retrieve(%data);

		# Set session
		if ( $self->create_new_session($user) ) {
			my $type = $self->get_user_type;
			redirect "/$type/start";
		}
		else {
			redirect '/login';
		}
	}
}


sub create_new_session {
	my $self    = shift;
	my $user_id = shift;

	my $session_id = md5_hex($user_id.localtime);
	my $session= Zuz::Sessions->insert(
		{	session_id    => $session_id,
			user_id       => $user_id,
		}
	);
	session zuz => $session->session_id;
	return $session->id ? 1 : 0; 
}


1;